package com.hxm.demo.newcoder;

import java.util.ArrayList;
import java.util.List;

/**
 * description: add a description
 *
 * @author huangxiaoming
 * @version 1.0.0
 * @date 2023/08/25 11:54:43
 */
public class TestBM10 {

    public static void main(String[] args) {
        ListNode pHead1 = new ListNode(1);
        pHead1.next = new ListNode(2);
        pHead1.next.next = new ListNode(3);
        pHead1.next.next.next = new ListNode(4);

        ListNode pHead2 = new ListNode(1);
        pHead2.next = new ListNode(3);
        pHead2.next.next = new ListNode(4);
        ListNode listNode = FindFirstCommonNode2(pHead1, pHead2);
        System.out.println(listNode);
    }

    public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        List<ListNode> list = new ArrayList<>();
        while (pHead1 != null) {
            list.add(pHead1);
            pHead1 = pHead1.next;
        }
        while (pHead2 != null) {
            if (list.contains(pHead2)) {
                return pHead2;
            }
            pHead2 = pHead2.next;
        }
        return null;
    }

    public static ListNode FindFirstCommonNode2(ListNode pHead1, ListNode pHead2) {
        ListNode l1 = pHead1;
        ListNode l2 = pHead2;
        while (l1 != l2) {
            l1 = (l1 == null) ? pHead2 : l1.next;
            l2 = (l2 == null) ? pHead1 : l2.next;
        }
        return l1;
    }
}
